package com.fdsc.erp.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fdsc.erp.entity.QuestionnaireEntity;
import com.fdsc.erp.service.QuestionnaireService;
import com.fdsc.erp.util.R;
import com.fdsc.erp.weixin.Config;
import com.fdsc.erp.weixin.CoreService;
import com.fdsc.erp.weixin.Utils.SignUtil;
import com.fdsc.erp.weixin.WeixinOauth2.SNSUserInfo;
import com.fdsc.erp.weixin.WeixinOauth2.WeixinOauth2Token;
import com.fdsc.erp.weixin.WeixinOauth2.WeixinOauth2TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("questionnaire")
public class QuestionnaireController {
    @Autowired
    QuestionnaireService questionnaireService;
    private final Logger logger = LoggerFactory.getLogger(QuestionnaireController.class);

    @RequestMapping("getWeixinUUid")
    public String getWeixinUUid(HttpServletResponse response, HttpServletRequest request, Model model) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            //用户同意授权后，能获取到code
            String code = request.getParameter("code");
            model.addAttribute("code", code);
            //用户同意授权
            if (!"authdeny".equals(code)) {
                //获取网页授权access_token
                WeixinOauth2Token weixinOauth2Token = WeixinOauth2TokenUtil.getOauthToken(Config.APPID, Config.APPSECRET, code);
                //网页授权接口访问凭证
                String accessToken = weixinOauth2Token.getAccessToken();
                //用户标识
                String openId = weixinOauth2Token.getOpenId();
                //获取用户信息
                SNSUserInfo snsUserInfo = WeixinOauth2TokenUtil.getSNSUserInfo(accessToken, openId);
                //设置要传递的参数
                request.setAttribute("snsUserInfo", snsUserInfo);
                model.addAttribute("openId", openId);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "/addAlumni";
    }

    @RequestMapping("getWeixinUUidToEdit")
    public String getWeixinUUidToEdit(HttpServletResponse response, HttpServletRequest request, Model model) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            //用户同意授权后，能获取到code
            String code = request.getParameter("code");
            model.addAttribute("code", code);
            //用户同意授权
            if (!"authdeny".equals(code)) {
                //获取网页授权access_token
                WeixinOauth2Token weixinOauth2Token = WeixinOauth2TokenUtil.getOauthToken(Config.APPID, Config.APPSECRET, code);
                //网页授权接口访问凭证
                String accessToken = weixinOauth2Token.getAccessToken();
                //用户标识
                String openId = weixinOauth2Token.getOpenId();
                //获取用户信息
                SNSUserInfo snsUserInfo = WeixinOauth2TokenUtil.getSNSUserInfo(accessToken, openId);
                //设置要传递的参数
                request.setAttribute("snsUserInfo", snsUserInfo);
                model.addAttribute("openId", openId);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "/editAlumni";
    }

    /**
     * 添加同学录
     *
     * @param questionnaireEntity
     * @return
     */
    @ResponseBody
    @RequestMapping("add")
    public String addQuestionnaire(QuestionnaireEntity questionnaireEntity) {
        try {
            String uuid=questionnaireEntity.getUuid();
            if(StringUtils.isNotBlank(uuid)){
                QuestionnaireEntity questionnaire = questionnaireService.selectOne(new EntityWrapper<>(new QuestionnaireEntity()).eq("uuid", questionnaireEntity.getUuid()));
                if (questionnaire != null && questionnaire.getId() != null) {
                    questionnaireEntity.setId(questionnaire.getId());
                    questionnaireService.updateById(questionnaireEntity);
                } else {
                    String id = "WX-" + System.currentTimeMillis();
//            UUID uuid=UUID.randomUUID();
                    questionnaireEntity.setId(id);
                    questionnaireService.insert(questionnaireEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }

    /**
     * 绑定同学录
     *
     * @param uuid
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("binding")
    public String bindingQuestionnaire(String uuid, String phone) {
        try {
            QuestionnaireEntity questionnaire = questionnaireService.selectOne(new EntityWrapper<>(new QuestionnaireEntity()).eq("电话", phone));
//            QuestionnaireEntity questionnaire=   questionnaireService.selectOne(new EntityWrapper<>(new QuestionnaireEntity()).eq("uuid",uuid));
            if (questionnaire != null && questionnaire.getId() != null && (questionnaire.getUuid() == null||"".equals(questionnaire.getUuid()))) {
                questionnaire.setUuid(uuid);
                questionnaireService.updateById(questionnaire);
            }else {
                return "error";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }

    /**
     * 查询同学录
     *
     * @param questionnaireEntity
     * @return
     */
    @ResponseBody
    @RequestMapping("selectQuestionnaire")
    public R selectQuestionnaire(QuestionnaireEntity questionnaireEntity) {
        try {
            List<QuestionnaireEntity> questionnaireEntityList = questionnaireService.selectQuestionnaireList(questionnaireEntity);
            return R.ok().put("list", questionnaireEntityList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }
    }

    /**
     * 根据id获取通讯录信息
     *
     * @param uuid
     * @return
     */
    @ResponseBody
    @RequestMapping("getQuestionnaireByUUId")
    public QuestionnaireEntity getQuestionnaireById(String uuid) {
        try {
            logger.info("uuid=" + uuid);
            QuestionnaireEntity questionnaireEntity=questionnaireService.selectOne(new EntityWrapper<>(new QuestionnaireEntity()).eq("uuid", uuid));
            if(questionnaireEntity!=null&&questionnaireEntity.getId()!=null){
                return questionnaireEntity;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取错误"+e.getMessage());
        }
        return null;
    }

    /**
     * 获取番号列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getDesignationList")
    public List<String> getDesignationList() {
        try {
            return questionnaireService.getDesignationList();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 微信验证
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("validateWeixin")
    public void validateWeixin(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //微信加密签名
        String signature = request.getParameter("signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = null;
        try {
            out = response.getWriter();
            //请求校验，若校验成功则原样返回，表示接入成功，否则接入失败
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                //调用核心服务类接收处理请求
                String respXml = CoreService.processRequest(request);
                out.print(respXml);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.close();
        out = null;
    }
}
